import {
  ColDef,
  ValueFormatterParams,
  ValueGetterParams,
} from 'ag-grid-community';
import { AgGridReact } from 'ag-grid-react';

import { Product } from '../types';

const currency = 'RUB';

type RowData = Product;

interface ProductsTableProps {
  data: Product[];
}

export const ProductsTable = ({ data }: ProductsTableProps) => {
  const currencyFormatter =
    <T, K>(currency?: string) =>
    (params: ValueFormatterParams<T, K>) =>
      `${Number(params.value ? params.value : 0).toFixed(2)} ${currency ?? ''}`;

  const columnDefs: ColDef[] = [
    {
      colId: 'name',
      field: 'name',
      headerName: 'Название',
    },
    {
      colId: 'sku',
      field: 'sku',
      headerName: 'Артикул',
    },
    {
      colId: 'category',
      headerName: 'Категория',
      valueGetter: ({ data }: ValueGetterParams<RowData>) => {
        return data?.process?.category?.name ?? '';
      },
    },
    {
      colId: 'defaultSellPrice',
      field: 'defaultSellPrice',
      headerName: 'Цена продажи по умолчанию',
      valueFormatter: currencyFormatter(currency),
    },
    {
      colId: 'cost',
      headerName: 'Стоимость',
      valueGetter: ({ data }: ValueGetterParams<RowData>) =>
        data &&
        (data.process.isMakingByDefault
          ? data.operationsCost + data.ingredientsCost
          : data.defaultBuyPrice),
      valueFormatter: currencyFormatter(currency),
    },
    {
      colId: 'profit',
      headerName: 'Доходность',
      valueGetter: (params: ValueGetterParams) =>
        (params.data.defaultSellPrice ?? 0) - params.getValue('cost'),
      valueFormatter: currencyFormatter(currency),
    },
    {
      colId: 'margin',
      headerName: 'Маржинальная доходность',
      valueGetter: (params: ValueGetterParams) =>
        params.getValue('defaultSellPrice') !== 0
          ? (params.getValue('profit') / params.getValue('defaultSellPrice')) *
            100
          : '',
      valueFormatter: ({ value }) => (value ? `${value.toFixed(2)} %` : ''),
    },
  ];

  return <AgGridReact rowData={data} columnDefs={columnDefs} />;
};
